#include <tri-fichier.h>

#define _BSD_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>

#include <config-client.h>
#include <constants.h>


int AddReport(char *serverName){
	char filePath[128]=CLIENT_REPORT_INCOMING; strcat(filePath, serverName);
	char dirPath[128]=CLIENT_DATABASE; strcat(dirPath, serverName);
	struct stat st;
	if(FileExists(filePath)){
		stat(dirPath, &st);
		if(!S_ISDIR(st.st_mode)){
			mkdir(dirPath, S_IRUSR | S_IWUSR);
		}
	}else{
		return 0;	
	}

	struct dirent **dirlist;
	int ret=scandir(dirPath, &dirlist, NULL, alphasort);
	if(ret==-1){
		return 0;
	}
	
	int i;
	for(i=ret-1;i>=0;--i){
		int nbreport;
		if(sscanf(dirlist[i]->d_name, "report%d", &nbreport)==1){
			char sFile[128], eFile[128];
			strcpy(sFile, dirPath); sprintf(sFile+strlen(sFile), "/report%.4d", nbreport);
			if(nbreport>=ConfMaxReport()){
				remove(sFile);
			}else{
				strcpy(eFile, dirPath); sprintf(eFile+strlen(eFile), "/report%.4d", nbreport+1);
				rename(sFile,eFile);
			}
		}
		free(dirlist[i]);
	}
	free(dirlist);
	char eFile[128]; strcpy(eFile, dirPath); strcat(eFile, "/report0000");
	rename(filePath, eFile);
}


void CleanDB(){
	struct stat st;
	stat(CLIENT_DATABASE, &st);
	if(!S_ISDIR(st.st_mode)){
			mkdir(CLIENT_DATABASE, S_IRUSR | S_IWUSR);
			return;
	}
	
	struct dirent **dirlist;
	int ret=scandir(CLIENT_DATABASE, &dirlist, NULL, alphasort);
	int i;
	char pPath[128];
	for(i=0;i<ret;++i){
		if(strcmp(dirlist[i]->d_name, ".")!=0 && strcmp(dirlist[i]->d_name, "..")!=0){
			int j=-1;
			while(ServerName(++j)!=NULL){
				if(strcmp(ServerName(j), dirlist[i]->d_name)==0) break;
			}
			strcpy(pPath, CLIENT_DATABASE); strcat(pPath, "/"); strcat(pPath, dirlist[i]->d_name);
			stat(pPath, &st);
			if(ServerName(j)==NULL || !S_ISDIR(st.st_mode)){
				char cmd[128] = "rm -rf ";
				strcat(cmd, pPath);
				system(cmd);
			}else{
				struct dirent **cdirlist;
				int k, nbreport;
				int ret2=scandir(pPath, &cdirlist, NULL, alphasort);
				char ppPath[128];
				for(k=0;k<ret2;++k){
					if(strcmp(cdirlist[k]->d_name, ".")!=0 && strcmp(cdirlist[k]->d_name, "..")!=0){
						int z=sscanf(cdirlist[k]->d_name, "report%4d", &nbreport);
						strcpy(ppPath, pPath); strcat(ppPath, "/"); strcat(ppPath, cdirlist[k]->d_name);
						stat(ppPath, &st);
						if(z!=1 || strlen(cdirlist[k]->d_name)!=10 || S_ISDIR(st.st_mode) || nbreport>ConfMaxReport()){
							char cmd[128] = "rm -rf ";
							strcat(cmd, ppPath);
							system(cmd);
						}
					}
					free(cdirlist[k]);
				}
				free(cdirlist);
			}
		}
		free(dirlist[i]);
	}
	free(dirlist);
}


